package it.carlom.stickyheader.example.animator;

import it.carlom.stickyheader.ResourceTable;
import it.carlom.stikkyheader.core.animator.AnimatorBuilder;
import it.carlom.stikkyheader.core.animator.HeaderStikkyAnimator;
import it.carlom.stikkyheader.core.utils.LogUtil;
import it.carlom.stikkyheader.core.utils.PxUtil;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;


public class IO2014HeaderAnimator extends HeaderStikkyAnimator {

    private Component mHeaderText;
    private int mHeightStartAnimation;
    private int mMinHeightTextHeader;
    private AnimatorValue mAnimatorValue;

    private boolean isCovering = false;
    private int mActionBarHeight;

    public IO2014HeaderAnimator() {
    }

    @Override
    public AnimatorBuilder getAnimatorBuilder() {
        Component image = getHeader().findComponentById(ResourceTable.Id_header_image);
        return new AnimatorBuilder()
                .applyVerticalParallax(image, 0.5f);
    }

    @Override
    protected void onAnimatorAttached() {
        super.onAnimatorAttached();
        mHeaderText = getHeader().findComponentById(ResourceTable.Id_header_text_layout);
        mActionBarHeight = (int) PxUtil.vp2px(35);
        mMinHeightTextHeader = (int) PxUtil.vp2px(65);
        mHeightStartAnimation = mActionBarHeight + mMinHeightTextHeader;
        mAnimatorValue = new AnimatorValue();
        mAnimatorValue.setDuration(200);
        //setLoopedCount 当前会出现 value值 多次调用的情况 且value值不定
        LogUtil.loge("onAnimatorAttached");
        mAnimatorValue.setValueUpdateListener((animatorValue, v) -> {
            LogUtil.loge("更新 value:" + v);
            int value;
            if (isCovering) {
                value = (int) (mMinHeightTextHeader + mActionBarHeight * (double) v);
            } else {
                value = (int) (mHeightStartAnimation - mActionBarHeight * (double) v);
            }
            ComponentContainer.LayoutConfig layoutParams = mHeaderText.getLayoutConfig();
            layoutParams.height = value;
            mHeaderText.setLayoutConfig(layoutParams);
        });
    }

    @Override
    public void onScroll(int scrolledY) {
        super.onScroll(scrolledY);
        double translatedY = getHeader().getTranslationY();
        double visibleHeightHeader = getHeightHeader() + translatedY;
        if (visibleHeightHeader <= mHeightStartAnimation && !isCovering) {
            isCovering = true;
            if (mAnimatorValue.isRunning()) {
                mAnimatorValue.end();
            }
            LogUtil.loge("更新 start");
            mAnimatorValue.start();
        } else if (visibleHeightHeader > mHeightStartAnimation && isCovering) {
            LogUtil.loge("更新 start2");
            isCovering = false;
            if (mAnimatorValue.isRunning()) {
                mAnimatorValue.end();
            }
            mAnimatorValue.start();
        }
    }
}